package Thread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import server.system.GeneralThreadPool;
import server.system.StreamUtil;

public class CheckThread implements Runnable {

	private final int _count ;
	
	public CheckThread(final int count){
		_count = count;
	}
	
	public void start(){
		GeneralThreadPool.getInstance().execute(this);
	}
	
	
	@Override
	public void run() {
		while(getCount() == _count){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
		}
		try {
			Thread.sleep(1500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		changeCFG();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.exit(0);
	}

	
	
	
	private int getCount(){
		try {
			ProcessBuilder pb = new ProcessBuilder("cmd" ,"/c", "tasklist" ,"/fo" ,"table");
			Process process = pb.start();
			BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line;
			int count = 0;
			while ((line = br.readLine()) != null) {
				if(line.startsWith("HIGO.exe")){
					count++;
				}
			}
			return count;
		} catch (IOException es) {
		}
		
		return -1;
	}
	private void changeCFG(){
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter("./HIGO.cfg", false));
			if(out !=null){
				out.write("[Setting]");
				out.newLine();
				out.write("UpdateInfo=iT44BHgIgxAduIT6YfjzUC5KyU5T6oLgbuO2AUoisDsXms2bCruUH10Bphl7+qT+WfzHWE4O60grvq3jHbTAUzEF1gFRuJOhYL2tSjAIkEtAvdz6bK2rUCoGj0BHtpmzXqvdEh8Pqll+u+f5V66KSRsf4Acg+a2vBOnIHw4GtV6FqBnvqbgHLDLO2cZOb8owYWSjnCTEmZoGM4tlKiPm1VyI6N8xOLxuDjPCxVqC7tVtcK9pUHHXzFeb99grOukjbTi023/PkcICZ9tlP2bmhS+Lz4hRKNx+dTi5zjqSjsVvIuJ0AXCCyUzQs8x6O+N5XzrJlgqK8JNqP68hVz7TgLfDW8zHbhxusC0ylQ==");
				out.newLine();
				out.write("[Background]");
				out.newLine();
				out.write("Enable=1");
				out.newLine();
				out.write("Bulletin=skin/Bulletin.bmp");
				out.newLine();
				out.write("Serverlist=skin/Serverlist.bmp");
				out.newLine();
				out.write("Button=skin/Button.bmp");
				out.newLine();
				out.write("ButtonTextColor=0xFFD700");
				out.newLine();
				out.flush();
			}
		} catch (final IOException e) {
			e.printStackTrace();
		}finally{
			StreamUtil.close(out);
		}
	}
	
	
	
}
